/* eslint-disable camelcase */
import SQLite from 'react-native-sqlite-storage';

SQLite.DEBUG(false);
SQLite.enablePromise(true);

const database_name = 'Test.db';
const database_version = '1.0';
const database_displayname = 'SQLite Test Database';
const database_size = 200000;

let db = null

const DbUtils = {

    init() {
        return db ? new Promise((resolve, reject) => { return resolve(db) })
            : SQLite.openDatabase(database_name, database_version, database_displayname, database_size).then(DB => {
                db = DB
                return db
            })
    },

    /**
     * 创建表
     * @param {*} sqlStatements 建表语句
     */
    createTables(sqlStatements, mCallBack) {
        let sqls = sqlStatements
        if (sqlStatements instanceof Array) {
            sqls = sqlStatements.join('')
        }
        this.call(sqls, null, mCallBack)
    },

    /**
     * 执行请求
     * @param {string} sqlStatement sql语句
     * @param {array} argumentArray 参数
     * @param {function} mCallBack 回调
     */
    call(sqlStatement, argumentArray = [], mCallBack) {
        this.init().then(DB => {
            DB.transaction(tx => {
                tx.executeSql(sqlStatement, argumentArray, (_, resultSet) => {
                    mCallBack && mCallBack(true, resultSet)
                }, (_, error) => {
                    mCallBack && mCallBack(false, error)
                });
            })
        }).catch(console.log);
    },


    close() {
        if (db) {
            db.close().then(status => {
                console.log(status)
                db = null
            }).catch(console.log)
        }
    },
}

export { DbUtils }